<template>
	<n-card>
		<!-- 搜索条件 -->
		<n-form inline>
			<n-form-item>
				<n-input
					v-model:value="searchKeyword"
					placeholder="昵称或OpenID"
					clearable
				/>
			</n-form-item>
			<n-form-item>
				<n-select
					style="width: 100px"
					v-model:value="subscribeStatus"
					:options="subscribeStatusOptions"
					placeholder="全部"
					clearable
				/>
			</n-form-item>
			<n-form-item>
				<n-space>
					<n-button type="primary" @click="fetchSubscribers">搜索</n-button>
					<n-button
						type="primary"
						@click="batchTagAction('tag')"
						:disabled="selectedSubscribers.length === 0"
						>批量打标签</n-button
					>
					<n-button
						type="warning"
						@click="batchTagAction('untag')"
						:disabled="selectedSubscribers.length === 0"
						>批量取消标签</n-button
					>
				</n-space>
			</n-form-item>
		</n-form>

		<!-- 用户列表 -->
		<n-data-table
			:data="subscribers"
			:columns="columns"
			:row-key="(row) => row.openId"
			:checked-row-keys="selectedSubscribers"
			@update:checked-row-keys="updateSelectedSubscribers"
			:pagination="pagination"
			@update:page="handlePageChange"
			@update:page-size="handlePageSizeChange"
		/>

		<!-- 用户详情对话框 -->
		<n-modal v-model:show="showDetailModal">
			<n-card
				style="
					width: 600px;
					height: 100%;
					position: fixed;
					right: 0px;
					top: 0px;
				"
				title="用户详情"
				:bordered="false"
				role="dialog"
				aria-modal="true"
			>
				<n-scrollbar v-if="selectedUser" style="max-height: 90vh">
					<n-space direction="horizontal" class="mb-4 flex-center">
						<n-avatar :src="selectedUser.avatarUrl" size="large" />
						<n-space direction="vertical" class="ml-4 flex-start">
							<n-thing :title="selectedUser.nickname || '隐藏用户'">
								<template #description>
									{{ selectedUser.openId }}
								</template>
							</n-thing>
						</n-space>
					</n-space>
					<n-descriptions label-placement="top" bordered :column="2">
						<n-descriptions-item>
							<template #label> UnionID </template>
							{{ selectedUser.unionId || "-" }}
						</n-descriptions-item>
						<n-descriptions-item>
							<template #label> 性别 </template>
							{{
								selectedUser.gender === 1
									? "男"
									: selectedUser.gender === 2
									? "女"
									: "未知"
							}}
						</n-descriptions-item>
						<n-descriptions-item>
							<template #label> 地区 </template>
							{{ selectedUser.country }} {{ selectedUser.province }}
							{{ selectedUser.city }}
						</n-descriptions-item>
						<n-descriptions-item>
							<template #label> 语言 </template>
							{{ selectedUser.language }}
						</n-descriptions-item>
						<n-descriptions-item>
							<template #label> 订阅状态 </template>
							{{ selectedUser.subscribeStatus === 1 ? "已订阅" : "未订阅" }}
						</n-descriptions-item>
						<n-descriptions-item>
							<template #label> 订阅时间 </template>
							{{ selectedUser.subscribeTime }}
						</n-descriptions-item>
						<n-descriptions-item>
							<template #label> 最近订阅时间 </template>
							{{ selectedUser.latestSubscribeTime }}
						</n-descriptions-item>
						<n-descriptions-item>
							<template #label> 订阅场景 </template>
							{{ selectedUser.subscribeScene }}
						</n-descriptions-item>
						<n-descriptions-item>
							<template #label> 所属标签 </template>
							{{ selectedUser.tagIds }}
						</n-descriptions-item>
						<n-descriptions-item>
							<template #label> 所属分组 </template>
							{{ selectedUser.groupId }}
						</n-descriptions-item>
						<n-descriptions-item>
							<template #label> 来源 </template>
							{{ selectedUser.userSource }}
						</n-descriptions-item>
						<n-descriptions-item>
							<template #label> 备注 </template>
							{{ selectedUser.remark || "-" }}
						</n-descriptions-item>
					</n-descriptions>
				</n-scrollbar>
			</n-card>
		</n-modal>

		<!-- 用户标签对话框 -->
		<n-modal v-model:show="showUserTagsModal">
			<n-card
				style="
					width: 600px;
					height: 100%;
					position: fixed;
					right: 0px;
					top: 0px;
				"
				title="用户标签"
				:bordered="false"
				role="dialog"
				aria-modal="true"
			>
				<n-list v-if="userTags.length > 0">
					<n-space direction="vertical">
						<n-badge
							:value="tag.count"
							:max="15"
							type="error"
							v-for="tag in userTags"
							:key="tag.tagId"
						>
							<n-tag type="success">
								{{ tag.name }}
							</n-tag>
						</n-badge>
					</n-space>
				</n-list>
				<div v-else class="text-center p-4 text-gray-400">暂无标签数据</div>
			</n-card>
		</n-modal>

		<!-- 批量标签操作对话框 -->
		<n-modal v-model:show="showBatchTagModal">
			<n-card
				style="
					width: 600px;
					height: 100%;
					position: fixed;
					right: 0px;
					top: 0px;
				"
				:title="batchTagTitle"
				:bordered="false"
				role="dialog"
				aria-modal="true"
			>
				<n-form>
					<n-form-item label="选择标签">
						<n-select
							v-model:value="selectedBatchTagId"
							:options="batchTagOptions"
							placeholder="请选择标签"
							filterable
						/>
					</n-form-item>
					<n-space justify="end" style="margin-top: 20px">
						<n-button @click="showBatchTagModal = false">取消</n-button>
						<n-button type="primary" @click="confirmBatchTagAction"
							>确定</n-button
						>
					</n-space>
				</n-form>
			</n-card>
		</n-modal>
	</n-card>
</template>

<script setup>
	import { ref, reactive, computed, onMounted } from "vue";
	import wechatSubscriberApi from "@server/api/wechatSubscriberApi";
	import wechatTagApi from "@server/api/wechatTagApi";
	// 替换 useDialog 为 useMessage
	import { useMessage, NSpace, NButton, NAvatar, NTag } from "naive-ui";
	const message = useMessage();

	// 用户列表数据
	const subscribers = ref([]);
	// 总条数
	const total = ref(0);
	// 选中的用户
	const selectedSubscribers = ref([]);
	// 当前选中的用户
	const selectedUser = ref(null);
	// 用户标签列表
	const userTags = ref([]);
	// 批量操作标签列表
	const batchTagOptions = ref([]);
	// 对话框状态
	const showDetailModal = ref(false);
	const showUserTagsModal = ref(false);
	const showBatchTagModal = ref(false);
	// 批量标签操作类型
	const batchTagType = ref("tag");
	const batchTagTitle = computed(() =>
		batchTagType.value === "tag" ? "批量打标签" : "批量取消标签"
	);
	// 选中的批量操作标签ID
	const selectedBatchTagId = ref(null);

	// 分页参数
	const pagination = reactive({
		page: 1,
		pageSize: 10,
		showSizePicker: true,
		pageSizes: [10, 20, 50, 100],
		showQuickJumper: true,
		showTotal: (total) => `共 ${total} 条数据`,
	});

	// 搜索参数
	const searchKeyword = ref("");
	const subscribeStatus = ref(null);

	// 订阅状态选项
	const subscribeStatusOptions = [
		{ label: "全部", value: null },
		{ label: "已订阅", value: 1 },
		{ label: "未订阅", value: 0 },
	];

	// 表格列配置
	const columns = [
		{
			type: "selection",
			width: 60,
			align: "center",
		},
		{
			title: "头像",
			key: "avatarUrl",
			width: 80,
			render: (row) => h("n-avatar", { src: row.avatarUrl }),
		},
		{
			title: "昵称",
			key: "nickname",
			width: 150,
		},
		{
			title: "OpenID",
			key: "openId",
			width: 250,
		},
		{
			title: "订阅状态",
			key: "subscribeStatus",
			width: 100,
			render: (row) =>
				h(
					NTag,
					{ type: row.subscribeStatus === 1 ? "success" : "default" },
					{ default: () => (row.subscribeStatus === 1 ? "已订阅" : "未订阅") }
				),
		},
		{
			title: "订阅时间",
			key: "subscribeTime",
			width: 180,
		},
		{
			title: "操作",
			key: "actions",
			width: 200,
			render: (row) =>
				h(NSpace, null, [
					h(
						NButton,
						{ size: "small", onClick: () => viewUserDetail(row) },
						{ default: () => "详情" }
					),
					h(
						NButton,
						{
							size: "small",
							type: "error",
							onClick: () => viewUserTags(row.openId),
						},
						{ default: () => "标签" }
					),
				]),
		},
	];

	// 获取用户列表 - 修改为使用 useMessage
	const fetchSubscribers = async () => {
		try {
			const result = await wechatSubscriberApi.getSubscriberList(
				pagination.page,
				pagination.pageSize,
				searchKeyword.value,
				subscribeStatus.value
			);
			subscribers.value = result.records;
			total.value = result.total;
		} catch (error) {
			console.error("获取用户列表失败:", error);
			message.error("获取用户列表失败");
		}
	};

	// 查看用户标签 - 修改为使用 useMessage
	const viewUserTags = async (openId) => {
		try {
			userTags.value = await wechatTagApi.getUserTags(openId);
			showUserTagsModal.value = true;
		} catch (error) {
			console.error("获取用户标签失败:", error);
			message.error("获取用户标签失败");
		}
	};

	// 确认批量标签操作 - 修改为使用 useMessage
	const confirmBatchTagAction = async () => {
		if (!selectedBatchTagId.value || selectedSubscribers.value.length === 0) {
			message.warning("请选择标签和用户");
			return;
		}

		try {
			if (batchTagType.value === "tag") {
				await wechatTagApi.batchTagUsers(
					selectedSubscribers.value,
					selectedBatchTagId.value
				);
				message.success("批量打标签成功");
			} else {
				await wechatTagApi.batchUntagUsers(
					selectedSubscribers.value,
					selectedBatchTagId.value
				);
				message.success("批量取消标签成功");
			}

			showBatchTagModal.value = false;
			// 刷新用户列表以更新标签信息
			await fetchSubscribers();
		} catch (error) {
			console.error("批量标签操作失败:", error);
			message.error("操作失败，请重试");
		}
	};

	// 获取标签列表（用于批量操作）
	const fetchTagOptions = async () => {
		try {
			const tags = await wechatTagApi.getTagList();
			batchTagOptions.value = tags.map((tag) => ({
				label: tag.name,
				value: tag.tagId,
			}));
		} catch (error) {
			console.error("获取标签列表失败:", error);
		}
	};

	// 更新选中的用户
	const updateSelectedSubscribers = (keys) => {
		selectedSubscribers.value = keys;
	};

	// 分页变化
	const handlePageChange = (page) => {
		pagination.page = page;
		fetchSubscribers();
	};

	// 每页条数变化
	const handlePageSizeChange = (pageSize) => {
		pagination.pageSize = pageSize;
		pagination.page = 1;
		fetchSubscribers();
	};

	// 查看用户详情
	const viewUserDetail = (user) => {
		selectedUser.value = user;
		showDetailModal.value = true;
	};

	// 批量标签操作 - 设置操作类型并显示对话框
	const batchTagAction = async (type) => {
		batchTagType.value = type;
		// 确保有标签数据
		await fetchTagOptions();
		showBatchTagModal.value = true;
	};

	// 组件挂载时加载数据
	onMounted(() => {
		fetchSubscribers();
		// 预加载标签列表，以便批量操作时能立即使用
		fetchTagOptions();
	});
</script>

<style scoped>
</style>